﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Controllers;
using WebApplication1.Controllers.Demain;
using WebApplication1.Demain.Hellper.Interface;

namespace WebApplication1.Demain.Hellper.Implementation
{
    public class EfRespositoryy<T> : IRespository<T> where T : BaseEntity
    {
        private readonly AdminDb db;

        private DbSet<T> _entity;

        protected DbSet<T> Entity 
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;

            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public EfRespositoryy(AdminDb admin)
        {
            db = admin;
        }

        public void Delete(T entity)
        {
            _entity.Remove(entity);

            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var del = Table.Where(x => x.Id == id).FirstOrDefault();

            Delete(del);
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
